package com.dongnao.jack.invocate;

import com.alibaba.fastjson.JSONObject;
import com.dongnao.jack.invocate.bean.HttpInvocateParamBean;
import com.dongnao.jack.loadbalance.NodeRegisterInfo;
import com.dongnao.jack.rmi.impl.RmiUtil;
import com.dongnao.jack.rmi.impl.SoaRemote;
import com.dongnao.jack.service.store.ParseServiceFactory;
import com.dongnao.jack.spring.parse.ProtocolConfig;
import com.dongnao.jack.spring.parse.ReferenceConfig;

public class RmiRegistryInvocate implements RegistryInvocate {

    @Override
    public String invoke(RegistryInvocation invocation) {

        // 获取到应用对象
        ReferenceConfig reference = invocation.getReference();

        NodeRegisterInfo registerInfo = invocation.getRegisterInfo();
        // JSONObject parseObject = JSONObject.parseObject(registerInfo.toString());
        ProtocolConfig protocol = ParseServiceFactory.getParseService(registerInfo.getType())
                .parseProtocol(registerInfo.getRegisterInfo().toString());

        try {
            SoaRemote remote = RmiUtil.getRmiRegisterInvocation(protocol.getHost(), protocol.getPort(), "soadubbormi");

            // 使用封装bean
            HttpInvocateParamBean bean = new HttpInvocateParamBean();
            bean.setArgs(invocation.getArgs());
            bean.setMethodName(invocation.getMethod().getName());
            // bean.setParameterTypes(invocation.getMethod().getParameterTypes());
            bean.setRef(ParseServiceFactory.getParseService(registerInfo.getType())
                    .parseRef(registerInfo.getRegisterInfo().toString()));

            // return HttpUtils.post(url, map);
            return remote.invoke(JSONObject.toJSONString(bean));
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return null;
    }

}
